package 实验八网络编程2;

import java.net.DatagramPacket;  
import java.net.DatagramSocket;  
import java.net.InetAddress;  
public class 八杠三服务端 {  
    private DatagramSocket socket;  
    private byte[] buffer = new byte[1024];  
  
    public 八杠三服务端(int port) throws Exception {  
        socket = new DatagramSocket(port);  
    }  
  
    public void receiveAndBroadcast(String clientAddress) throws Exception {  
        while (true) {  
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);  
            socket.receive(packet);  
            String message = new String(packet.getData(), 0, packet.getLength());  
            System.out.println("Received message from " + clientAddress + ": " + message);  
            broadcastMessage(clientAddress, message);  
        }  
    }  
    private void broadcastMessage(String clientAddress, String message) throws Exception {  
        InetAddress address = InetAddress.getByName(clientAddress);  
        DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, address, socket.getLocalPort());  
        socket.send(packet);  
    }  
}